﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Serialization;
using System.Text;
using Core.Helper;

namespace Core.Model
{
    [DataContract]
    public class Operation
    {
        [DataMember]
        public string Id { get; set; }
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public bool IsAscii { get; set; }
        [DataMember]
        public bool NeedReply { get; set; }
        [DataMember]
        public string DevTypeId { get; set; }
        [DataMember]
        public string MsgContent { get; set; }
       

        private byte[] msgBuffer;
        public byte[] MsgBuffer
        {
            get
            {
                if (msgBuffer == null&&!string.IsNullOrEmpty(MsgContent))
                {
                    try
                    {
                        if (IsAscii)
                        {
                            msgBuffer = Encoding.ASCII.GetBytes(MsgContent);
                        }
                        else
                        {
                            string[] bytes = MsgContent.Split(' ');
                            List<byte> dataBytes = new List<byte>();
                            foreach (string b in bytes)
                            {
                                dataBytes.Add(Byte.Parse(b,NumberStyles.HexNumber));
                            }
                            msgBuffer = dataBytes.ToArray();
                        }
                    }
                    catch
                    {
                    }
                }
                return msgBuffer;
            }
        }
        [DataMember]
        public int Timeout { get; set; }

        public Operation()
        {
            Id = IdHelper.GuidToString();
            Name = "新操作";
            IsAscii = false;
            NeedReply = false;
            
        }

        public Operation(Operation source)
        {
            this.Id = source.Id;
            this.IsAscii = source.IsAscii;
            this.Name = source.Name;
            this.Timeout = source.Timeout;
            this.DevTypeId = source.DevTypeId;
            this.NeedReply = source.NeedReply;
            this.MsgContent = source.MsgContent;
        }
    }
}
